import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:talking/tools/config.dart';

import '../bean/bean.dart';
import '../tools/paint.dart';

class Login extends StatefulWidget {
  @override
  LoginPage createState() => LoginPage();
}

class LoginPage extends State<Login> with TickerProviderStateMixin {
  List<BobbleBean> _bobbleList = [];
  Random _random = new Random(DateTime.now().microsecondsSinceEpoch);
  double _maxSpeed = 1.0;
  double _maxRadius = 100;
  double _maxTheta = 2 * pi;
  late AnimationController _animationController;
  bool autoLogin = true;
  var emailController = TextEditingController();
  var passController = TextEditingController();
  bool obscureText = true;
  var errorText;
  Future<void> autoLoginVerity() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (prefs.getBool("autoLogin") ?? false) {
      var dio = Dio();
      if ((await dio.get(
                  "${Constant.BASE_URL}user/verify/?email=${prefs.getString("email")}&password=${prefs.getString("password")}"))
              .data
              .toString() ==
          "验证成功") {
        Navigator.of(context).pushReplacementNamed('home');
      }
    } else {
      setState(() {
        emailController.text = prefs.getString("email") ?? "";
      });
    }
  }

  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 20; i++) {
      BobbleBean bean = BobbleBean();
      bean.color = Color.fromARGB(_random.nextInt(200), 255, 255, 255);
      bean.offset = Offset(-1, -1);
      bean.speed = _random.nextDouble() * _maxSpeed;
      bean.radius = _random.nextDouble() * _maxRadius;
      bean.theta = _random.nextDouble() * _maxTheta;
      _bobbleList.add(bean);
    }
    _animationController =
        AnimationController(vsync: this, duration: Duration(seconds: 5));
    _animationController.addListener(() {
      setState(() {});
    });
    _animationController.repeat();
    emailController.addListener(() {
      setState(() {
        errorText = null;
      });
    });
    autoLoginVerity();
  }

  @override
  void dispose() {
    _animationController.dispose();
    passController.dispose();
    emailController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("登录"),
      ),
      body: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
                gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                  Colors.lightBlueAccent.withOpacity(0.3),
                  Colors.lightBlue.withOpacity(0.3),
                  Colors.blue.withOpacity(0.3),
                ])),
          ),
          CustomPaint(
            size: MediaQuery.of(context).size,
            painter: MyPainter(list: _bobbleList, random: _random),
          ),
          Container(
            color: Colors.white.withOpacity(0.2),
          ),
          Container(
            width: double.infinity,
            height: double.infinity,
            alignment: Alignment.bottomCenter,
            child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 30),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(bottom: 10),
                      child: TextField(
                        controller: emailController,
                        autofocus: true,
                        textInputAction: TextInputAction.next,
                        decoration: InputDecoration(
                            errorText: errorText,
                            suffixIcon: InkWell(
                              child: Icon(Icons.close),
                              onTap: () {
                                emailController.clear();
                              },
                            ),
                            labelText: "邮箱",
                            prefixIcon: const Icon(Icons.email),
                            border: OutlineInputBorder(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10)),
                                borderSide: BorderSide(color: Colors.blue))),
                      ),
                    ),
                    TextField(
                      controller: passController,
                      textInputAction: TextInputAction.go,
                      obscureText: obscureText,
                      decoration: InputDecoration(
                        suffixIcon: InkWell(
                          child: obscureText
                              ? Icon(Icons.remove_red_eye)
                              : Icon(Icons.remove_red_eye_outlined),
                          onTap: () {
                            setState(() {
                              obscureText = !obscureText;
                            });
                          },
                        ),
                        prefixIcon: const Icon(Icons.lock),
                        labelText: "密码",
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(10)),
                            borderSide: BorderSide(color: Colors.blue)),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.all(10),
                      child: CheckboxListTile(
                        title: const Text('记住密码'),
                        value: this.autoLogin,
                        onChanged: (bool? value) {
                          setState(() {
                            this.autoLogin = value!;
                          });
                        },
                      ),
                    ),
                    ElevatedButton(
                      onPressed: () async {
                        var dio = Dio();
                        String url =
                            "${Constant.BASE_URL}user/verify/?email=${emailController.text}&password=${passController.text}";
                        if ((await dio.get(url)).data.toString() == "验证成功") {
                          SharedPreferences prefs =
                              await SharedPreferences.getInstance();
                          prefs.setString("email", emailController.text);
                          prefs.setString("password", passController.text);
                          prefs.setBool("autoLogin", autoLogin);
                          Navigator.of(context).pushReplacementNamed('home');
                        } else {
                          setState(() {
                            errorText = "登录失败";
                          });
                        }
                      },
                      child: const Text("登录"),
                      style: ButtonStyle(
                        minimumSize: MaterialStateProperty.all(
                            Size(double.infinity, 40)),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(bottom: 20),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          OutlinedButton(
                            onPressed: () {
                              Navigator.of(context)
                                  .pushNamed("forgetPassword")
                                  .then((isOk) async {
                                if (isOk.toString() == "found") {
                                  Navigator.of(context)
                                      .pushReplacementNamed("home");
                                }
                              });
                            },
                            child: Text("找回密码"),
                            style: ButtonStyle(
                              minimumSize:
                                  MaterialStateProperty.all(Size(145, 40)),
                            ),
                          ),
                          OutlinedButton(
                            onPressed: () {
                              Navigator.of(context)
                                  .pushNamed("sign")
                                  .then((isOk) async {
                                if (isOk.toString() == "loginSuccess") {
                                  Navigator.of(context)
                                      .pushReplacementNamed("home");
                                }
                              });
                            },
                            child: Text("注册"),
                            style: ButtonStyle(
                              minimumSize:
                                  MaterialStateProperty.all(Size(145, 40)),
                            ),
                          ),
                        ],
                      ),
                    )
                  ],
                )),
          )
        ],
      ),
    );
  }
}
